<!-- src/pages/CalendarPage.vue -->
<template>
  <div class="calendar-container">
    <!-- 顶部导航栏 -->
    <CalendarHeader
      :sidebar-collapsed="sidebarCollapsed"
      :current-view="currentView"
      :selected-date="selectedDate"
      @toggle-sidebar="toggleSidebar"
      @go-today="goToToday"
      @previous-period="previousPeriod"
      @next-period="nextPeriod"
      @show-search="showSearch"
      @show-help="showHelp"
      @show-settings="showSettings"
      @change-view="changeView"
      @go-calendar-page="goCalendarPage"
      @go-task-page="goTaskPage"
      @toggle-grid="toggleGrid"
      @show-user-menu="showUserMenu"
    />

    <div class="main-content">
      <!-- 左侧边栏 -->
      <CalendarSidebar
        :sidebar-collapsed="sidebarCollapsed"
        :mini-calendar-month="miniCalendarMonth"
        :mini-calendar-year="miniCalendarYear"
        :mini-calendar-days="miniCalendarDays"
        :username="store.username"
        @create-event="createEvent"
        @previous-month="previousMonth"
        @next-month="nextMonth"
        @select-date="selectDate"
      />

      <!-- 主日历区域 -->
      <CalendarMain
        :current-view="currentView"
        :selected-date="selectedDate"
        :current-year="currentYear"
        :current-month="currentMonth"
        :year-months="yearMonths"
        :month-days="monthDays"
        :week-days="weekDays"
        :time-slots="timeSlots"
        @select-month="selectMonth"
        @select-year-date="selectYearDate"
        @select-month-date="selectMonthDate"
        @choose-time-slot="chooseTimeSlot"
        @choose-day-time-slot="chooseDayTimeSlot"
        @go-to-day-view="handleGoToDayView"
      />

      <!-- 右侧工具栏 -->
      <CalendarToolbar
        @show-picture-reader="showPictureReader"
        @show-tasks-list="showTasksList"
        @show-contacts="showContacts"
        @show-maps="showMaps"
        @add-more="addMore"
      />
    </div>


    <!-- 用户卡片 -->
    <UserCard
      :show-user-card="showUserCard"
      @close-user-card="closeUserCard"
      @manage-account="handleManageAccount"
      @logout="handleLogout"
    />

    <!-- 图片读取器 -->
    <PictureReader
      v-if="isPictureReaderShow"
      @close="closePictureReader"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { useCardStore } from '@/store/card'

// 导入组件
import CalendarHeader from '@/components/Calendar/CalendarHeader.vue'
import CalendarSidebar from '@/components/Calendar/CalendarSidebar.vue'
import CalendarMain from '@/components/Calendar/CalendarMain.vue'
import CalendarToolbar from '@/components/Calendar/CalendarToolbar.vue'
import UserCard from '@/components/Calendar/UserCard.vue'
import PictureReader from '@/components/Calendar/PictureReader.vue'
import type { activityCard, missionCard } from '@/types/card'
import type { DayData, MonthData } from '@/types/timeData'

const router = useRouter()
const store = useUserStore()

// 响应式数据
const sidebarCollapsed = ref(false)
const currentView = ref('week') // 默认周视图
const isPictureReaderShow = ref(false)

// 主日历相关数据
const currentMonth = ref(new Date().getMonth())
const currentYear = ref(new Date().getFullYear())
const selectedDate = ref(new Date())

// 迷你日历的独立月份状态
const miniCalendarMonth = ref(new Date().getMonth())
const miniCalendarYear = ref(new Date().getFullYear())

// 星期标题
const weekDaysShort = ['日', '一', '二', '三', '四', '五', '六']
// 完整的星期名称（用于月视图）
const weekDaysFull = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']

// 农历数据
const lunarMonths = ['正月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '冬月', '腊月']
const lunarDays = ['初一', '初二', '初三', '初四', '初五', '初六', '初七', '初八', '初九', '初十',
                    '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十',
                    '廿一', '廿二', '廿三', '廿四', '廿五', '廿六', '廿七', '廿八', '廿九', '三十']

// 计算属性
const miniCalendarDays = computed(() => {
  return generateMonthDays(miniCalendarYear.value, miniCalendarMonth.value)
})

// 周视图数据
const weekDays = computed(() => {
  const baseDate = new Date(selectedDate.value)
  const weekStart = new Date(baseDate)
  weekStart.setDate(baseDate.getDate() - baseDate.getDay()) // 设置为周日的日期
  
  const days = []
  for (let i = 0; i < 7; i++) {
    const dayDate = new Date(weekStart)
    dayDate.setDate(weekStart.getDate() + i)
    
    // 简化的农历显示
    const lunarDay = lunarDays[dayDate.getDate() - 1] || '三十'
    
    days.push({
      name: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][dayDate.getDay()],
      date: dayDate.getDate(),
      lunar: lunarDay,
      fullDate: dayDate
    })
  }
  return days
})

// 年视图月份数据
const yearMonths = computed(() => {
  const months = []
  for (let i = 0; i < 12; i++) {
    const monthDate = new Date(currentYear.value, i, 1)
    const monthDays = generateMonthDays(currentYear.value, i)
    
    months.push({
      name: `${i + 1}月`,
      month: i,
      year: currentYear.value,
      days: monthDays
    })
  }
  return months
})

// 月视图日期数据
const monthDays = computed(() => {
  return generateMonthDays(selectedDate.value.getFullYear(), selectedDate.value.getMonth())
})

// 生成月份天数数据
const generateMonthDays = (year: number, month: number) => {
  const days = []
  const firstDayOfMonth = new Date(year, month, 1)
  const lastDayOfMonth = new Date(year, month + 1, 0)
  const firstDayWeek = firstDayOfMonth.getDay() // 0 = 周日, 6 = 周六
  
  // 添加上个月的日期
  const prevMonthLastDay = new Date(year, month, 0).getDate()
  for (let i = firstDayWeek - 1; i >= 0; i--) {
    const date = prevMonthLastDay - i
    const fullDate = new Date(year, month - 1, date)
    
    // 简化的农历显示
    const lunarDay = lunarDays[fullDate.getDate() - 1] || '三十'
    
    days.push({
      date,
      isCurrentMonth: false,
      isToday: false,
      isSelected: false,
      lunar: lunarDay,
      fullDate
    })
  }
  
  // 添加当前月的日期
  const today = new Date()
  for (let i = 1; i <= lastDayOfMonth.getDate(); i++) {
    const fullDate = new Date(year, month, i)
    const isToday = today.getDate() === i && 
                   today.getMonth() === month && 
                   today.getFullYear() === year
    
    const isSelected = selectedDate.value.getDate() === i && 
                      selectedDate.value.getMonth() === month && 
                      selectedDate.value.getFullYear() === year
    
    // 简化的农历显示
    const lunarDay = lunarDays[fullDate.getDate() - 1] || '三十'
    
    days.push({
      date: i,
      isCurrentMonth: true,
      isToday,
      isSelected,
      lunar: lunarDay,
      fullDate
    })
  }
  
  // 添加下个月的日期
  const totalCells = 42 // 6行7列
  const nextMonthDays = totalCells - days.length
  for (let i = 1; i <= nextMonthDays; i++) {
    const fullDate = new Date(year, month + 1, i)
    
    // 简化的农历显示
    const lunarDay = lunarDays[fullDate.getDate() - 1] || '三十'
    
    days.push({
      date: i,
      isCurrentMonth: false,
      isToday: false,
      isSelected: false,
      lunar: lunarDay,
      fullDate
    })
  }
  
  return days
}

// 时间段
const timeSlots = ref(['凌晨1点', '凌晨2点', '凌晨3点', '凌晨4点', '凌晨5点', '上午6点', '上午7点', '上午8点', '上午9点', '上午10点', '上午11点', '中午12点', '下午1点', '下午2点', '下午3点', '下午4点', '下午5点', '下午6点', '傍晚7点', '傍晚8点', '傍晚9点', '夜间10点', '夜间11点', '午夜12点'])

// 卡片相关
const cardStore = useCardStore()

// 监听主日历日期变化，同步迷你日历显示
watch(selectedDate, (newDate) => {
  miniCalendarMonth.value = newDate.getMonth()
  miniCalendarYear.value = newDate.getFullYear()
}, { immediate: true })

// 监听年份变化，确保年视图数据正确更新
watch([currentYear, currentView], () => {
  if (currentView.value === 'year') {
    // 通过重新赋值触发响应式更新
    const year = currentYear.value
  }
})

// 用户卡片显示状态
const showUserCard = ref(false)

// 显示用户菜单卡片
const showUserMenu = () => {
  showUserCard.value = true
}

// 关闭用户菜单卡片
const closeUserCard = () => {
  showUserCard.value = false
}

// 管理账号功能
const handleManageAccount = () => {
  // TODO: 实现管理账号功能
  ElMessage.info('管理账号')
  closeUserCard()
}

// 退出账号功能  
const handleLogout = () => {
  store.logout()
  closeUserCard()
  router.push('/login')
}

// 点击外部关闭卡片
const handleClickOutside = (event: MouseEvent) => {
  const userCard = document.querySelector('.user-card')
  const userAvatar = document.querySelector('.user-avatar')
  
  if (
    showUserCard.value && 
    userCard && 
    !userCard.contains(event.target as Node) &&
    userAvatar &&
    !userAvatar.contains(event.target as Node)
  ) {
    closeUserCard()
  }
}

// 监听点击事件
onMounted(async () => {
  document.addEventListener('click', handleClickOutside)
  // 初始化卡片数据
  if (cardStore.missionCards.length === 0 && cardStore.activityCards.length === 0) {
    await cardStore.initializeCards()
  }
  // 初始化任务列表显示状态
  await cardStore.initTaskListVisibility()
})

// 迷你日历功能
const previousMonth = () => {
  if (miniCalendarMonth.value === 0) {
    miniCalendarMonth.value = 11
    miniCalendarYear.value--
  } else {
    miniCalendarMonth.value--
  }
}

const nextMonth = () => {
  if (miniCalendarMonth.value === 11) {
    miniCalendarMonth.value = 0
    miniCalendarYear.value++
  } else {
    miniCalendarMonth.value++
  }
}

const selectDate = (day: any) => {
  selectedDate.value = day.fullDate
  
  // 如果选择的是其他月份的日期，切换到对应的月份
  if (!day.isCurrentMonth) {
    currentMonth.value = day.fullDate.getMonth()
    currentYear.value = day.fullDate.getFullYear()
  }
}

const goToToday = () => {
  const today = new Date()
  selectedDate.value = today
  currentMonth.value = today.getMonth()
  currentYear.value = today.getFullYear()
}

const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

// 根据当前视图切换时间段
const previousPeriod = () => {
  if (currentView.value === 'week') {
    selectedDate.value = new Date(selectedDate.value.setDate(selectedDate.value.getDate() - 7))
  } else if (currentView.value === 'month') {
    currentMonth.value--
    if (currentMonth.value < 0) {
      currentMonth.value = 11
      currentYear.value--
    }
    selectedDate.value = new Date(currentYear.value, currentMonth.value, 1)
  } else if (currentView.value === 'day') {
    selectedDate.value = new Date(selectedDate.value.setDate(selectedDate.value.getDate() - 1))
  } else if (currentView.value === 'year') {
    currentYear.value--
    selectedDate.value = new Date(currentYear.value, 0, 1)
    // 强制触发年视图更新
    yearMonths.value // 访问计算属性以触发重新计算
  }

  // 主日历切换时，迷你日历同步更新到对应的月份
  miniCalendarMonth.value = selectedDate.value.getMonth()
  miniCalendarYear.value = selectedDate.value.getFullYear()
}

const nextPeriod = () => {
  if (currentView.value === 'week') {
    selectedDate.value = new Date(selectedDate.value.setDate(selectedDate.value.getDate() + 7))
  } else if (currentView.value === 'month') {
    currentMonth.value++
    if (currentMonth.value > 11) {
      currentMonth.value = 0
      currentYear.value++
    }
    selectedDate.value = new Date(currentYear.value, currentMonth.value, 1)
  } else if (currentView.value === 'day') {
    selectedDate.value = new Date(selectedDate.value.setDate(selectedDate.value.getDate() + 1))
  } else if (currentView.value === 'year') {
    currentYear.value++
    selectedDate.value = new Date(currentYear.value, 0, 1)
    // 强制触发年视图更新
    yearMonths.value // 访问计算属性以触发重新计算
  }

  // 主日历切换时，迷你日历同步更新到对应的月份
  miniCalendarMonth.value = selectedDate.value.getMonth()
  miniCalendarYear.value = selectedDate.value.getFullYear()
}

const showSearch = () => {
  ElMessage.info('显示搜索功能')
}

const showHelp = () => {
  ElMessage.info('显示帮助信息')
}

const showSettings = () => {
  ElMessage.info('显示设置面板')
}

// 切换视图
const changeView = (view: string) => {
  currentView.value = view
}

const goCalendarPage = () => {
  router.push('/calendar')
}

const goTaskPage = () => {
  router.push('/task')
}

const toggleGrid = () => {
  ElMessage.info('切换网格显示')
}

const createEvent = () => {
  ElMessage.info('创建新事件')
}

// 将 hourIndex 映射为 24 小时制小时数
// timeSlots: ['凌晨1点', '凌晨2点', ..., '上午7点', ...]
// hourIndex 0 -> 1点, hourIndex 6 -> 7点, hourIndex 9 -> 10点
const mapIndexToHour = (index: number) => index + 1

// 周视图时间段选择（事件传递给 WeekView 处理）
const chooseTimeSlot = (day: DayData, hourIndex: number, event: MouseEvent) => {
  // WeekView 内部会处理这个事件
}

// 日视图时间段选择（事件传递给 DayView 处理）
const chooseDayTimeSlot = (hourIndex: number) => {
  // DayView 内部会处理这个事件
}

// 年视图月份选择
const selectMonth = (month: MonthData) => {
  currentMonth.value = month.month
  currentYear.value = month.year
  selectedDate.value = new Date(month.year, month.month, 1)
  currentView.value = 'month'

  miniCalendarMonth.value = month.month
  miniCalendarYear.value = month.year
}

// 年视图日期选择
const selectYearDate = (day: DayData) => {
  selectedDate.value = day.fullDate
  ElMessage.info(`选中的日期: ${day.fullDate.getFullYear()}年${day.fullDate.getMonth() + 1}月${day.date}日`)
}

// 月视图日期选择
const selectMonthDate = (day: DayData) => {
  selectedDate.value = day.fullDate
  ElMessage.info(`选中的日期: ${day.fullDate.getFullYear()}年${day.fullDate.getMonth() + 1}月${day.date}日`)
}

// 年视图卡片跳转到日视图
const handleGoToDayView = (date: Date) => {
  selectedDate.value = date
  currentView.value = 'day'

  miniCalendarMonth.value = date.getMonth()
  miniCalendarYear.value = date.getFullYear()
}


const showPictureReader = () => {
  isPictureReaderShow.value = true
}
const closePictureReader = () => {
  isPictureReaderShow.value = false
}

const showTasksList = () => {
  ElMessage.info('显示任务列表')
}

const showContacts = () => {
  ElMessage.info('显示联系人')
}

const showMaps = () => {
  ElMessage.info('显示地图')
}

const addMore = () => {
  ElMessage.info('添加更多功能')
}
</script>

<style scoped>
.calendar-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #ffffff;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.1);
  z-index: 999;
}
</style>